# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: taekwon

import datetime
import logging
import pprint
import sys

from tornado import gen
from tornado.ioloop import IOLoop

from coin.base.config import Config
from coin.exchange.base.order_gateway import OrderSide, OrderType
from coin.exchange.gopax.order_gateway import GopaxOrderGateway
from coin.exchange.gopax.kr_rest.currency import GopaxCurrency
from coin.exchange.gopax.kr_rest.product import GopaxProduct

from coin.flow.simple_queue import SimpleQueue


class TestDriver(object):
  def __init__(self, ioloop):
    self._ioloop = ioloop
    self._og = GopaxOrderGateway([GopaxCurrency.FromStr('EOS'), GopaxCurrency.FromStr('KRW')],
                                 [GopaxProduct.FromStr('EOS-KRW')],
                                 Config.from_config_filename('/home/taekwon/gopax_api_key.json'))
    queue = SimpleQueue('q')
    self._og.start(queue, self._ioloop)
    self._ioloop.add_timeout(datetime.timedelta(seconds=5), self.print_balance)
    self._ioloop.add_timeout(datetime.timedelta(seconds=10), self.loop)

  def print_balance(self):
    if self._og.is_ready():
      print('------------------------')
      print(datetime.datetime.now())
      print('EOS', self._og.get_balance('EOS'))
      print('KRW', self._og.get_balance('KRW'))
      pprint.pprint(self._og.get_working_order())
    self._ioloop.add_timeout(datetime.timedelta(seconds=10), self.print_balance)

  @gen.coroutine
  def loop(self):
    self._og.cancel_all()
    yield gen.sleep(20)

    product = GopaxProduct.FromStr('EOS-KRW')

    self._og.submit(product, 5000., 1.1, OrderSide.SELL, OrderType.LIMIT)
    self._og.submit(product, 3000., 0.8, OrderSide.BUY, OrderType.LIMIT)
    self._og.submit(product, 5000., 1.1, OrderSide.SELL, OrderType.LIMIT)
    self._og.submit(product, 3000., 0.8, OrderSide.BUY, OrderType.LIMIT)
    self._og.submit(product, 5000., 1.1, OrderSide.SELL, OrderType.LIMIT)
    self._og.submit(product, 3000., 0.8, OrderSide.BUY, OrderType.LIMIT)

    yield gen.sleep(20)
    self._og.cancel_all()


def main(argv):
  ioloop = IOLoop.current()
  driver = TestDriver(ioloop)
  try:
    ioloop.start()
  except KeyboardInterrupt:
    pass


if __name__ == '__main__':
  logging.basicConfig(level='DEBUG', format='%(levelname)s %(asctime)s %(name)s] %(message)s')
  sys.exit(main(sys.argv))
